package cn.tedu.mall.seckill.controller;

import cn.tedu.mall.common.exception.CoolSharkServiceException;
import cn.tedu.mall.common.restful.JsonResult;
import cn.tedu.mall.common.restful.ResponseCode;
import cn.tedu.mall.pojo.seckill.dto.SeckillOrderAddDTO;
import cn.tedu.mall.pojo.seckill.vo.SeckillCommitVO;
import cn.tedu.mall.seckill.exception.SeckillBlockError;
import cn.tedu.mall.seckill.exception.SeckillFallbackError;
import cn.tedu.mall.seckill.service.ISeckillService;
import cn.tedu.mall.seckill.utils.SeckillCacheUtils;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/seckill")
@Api(tags = "提交秒杀订单")
public class SeckillController {
    @Autowired
    private ISeckillService seckillService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/{randCode}")
    @ApiOperation("随机码验证和提交秒杀订单")
    @ApiImplicitParam(value = "随机码",name = "randCode",dataType = "string")
    @PreAuthorize("hasRole('user')")
    @SentinelResource(value = "seckill-order",
    blockHandlerClass = SeckillBlockError.class,blockHandler = "blockError",
    fallbackClass = SeckillFallbackError.class,fallback = "fallbackError")
    public JsonResult<SeckillCommitVO> addSeckillOrder(@PathVariable String randCode,
                                                       SeckillOrderAddDTO seckillOrderAddDTO){
        //获取随机码的key
        Long spuId = seckillOrderAddDTO.getSpuId();
        String randCodeKey = SeckillCacheUtils.getRandCodeKey(spuId);
        //判断是否存在该key
        if(redisTemplate.hasKey(randCodeKey)){
            //获取随机码
            String redisRandCode = redisTemplate.boundValueOps(randCodeKey).get()+ "";
            //判断redisRandCode是否为null
            if (redisRandCode==null)
                throw new CoolSharkServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"服务器内部出现异常，请联系客服");
            //页码传递的随机码和redis中的随机码是否一致
            if(!randCode.equals(redisRandCode))
                throw new CoolSharkServiceException(ResponseCode.NOT_FOUND,"没有指定的商品(controller-value)");
            //以上程序都没有任何问题，执行购买程序
            SeckillCommitVO seckillCommitVO = seckillService.commitSeckill(seckillOrderAddDTO);
            return JsonResult.ok(seckillCommitVO);
        }else{
            //没有这个key，终止程序运行
            throw new CoolSharkServiceException(ResponseCode.NOT_FOUND,"没有该商品(controller-key)");
        }
    }
}
